<!--apiruncase-->
<template>
  <section>
    <br />
    <el-form :model="form" ref="form" :rules="FormRules">
      <div style="border: 1px solid #e6e6e6;margin-bottom: 10px;padding:15px">
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item
              label="所属项目:"
              label-width="83px"
              prop="getProjectFirstID"
            >
              <el-select
                v-model="form.getProjectFirstID"
                placeholder="请选择项目列表"
                @change="getInterface"
              >
                <el-option
                  v-for="(item, index) in project"
                  :key="index + ''"
                  :label="item.project_name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="验证环境:"
              label-width="83px"
              prop="getEnvironmentFirstID"
            >
              <el-select
                v-model="form.getEnvironmentFirstID"
                placeholder="请选择验证环境"
                required="true"
              >
                <el-option
                  v-for="(item, index) in env"
                  :key="index + ''"
                  :label="item.env_name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="18">
          <el-col :span="18">
            <el-form-item label="用例分类:" label-width="83px">
              <template>
                <el-radio-group v-model="radio3" @change="radioChange">
                  <el-radio-button label="0" border>疏通测试</el-radio-button>
                  <el-radio-button label="1" border>逻辑测试</el-radio-button>
                  <el-radio-button label="2" border>常规校验</el-radio-button>
                  <el-radio-button label="3" border
                    >全&nbsp;&nbsp;部</el-radio-button
                  >
                </el-radio-group>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <el-row :span="22">
        <el-collapse v-model="activeNames" @change="handleChange">
          <el-collapse-item title="选择执行接口" name="2"
            ><a class="color-red"
              >注:未维护用例的接口被执行会直接定为【执行失败】</a
            >
            <div style="margin: 5px">
              <el-row :span="24"> </el-row>
            </div>
            <el-table
              :data="runPlan"
              highlight-current-row
              :class="add"
              @selection-change="selsChange"
            >
              <el-table-column type="selection" min-width="5%">
              </el-table-column>
              <el-table-column label="接口id" min-width="14%">
                <template slot-scope="scope">
                  <span class="over-content">{{ scope.row.id }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="接口名称"
                min-width="45%"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <span class="over-content">{{
                    scope.row.interface_name_zh
                  }}</span>
                </template>
              </el-table-column>

              <el-table-column label="疏通测试数量" min-width="14%">
                <template slot-scope="scope">
                  <span class="over-content">{{ scope.row.count0 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="逻辑测试数量" min-width="14%">
                <template slot-scope="scope">
                  <span class="over-content">{{ scope.row.count1 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="mock" min-width="14%">
                <template slot-scope="scope">
                  <el-checkbox
                    :checked="
                      sels.map((item) => item.id).indexOf(scope.row.id) == 0
                    "
                    @change="subProj(scope.row)"
                    :disabled="
                      sels.map((item) => item.id).indexOf(scope.row.id) == -1
                    "
                  >
                  </el-checkbox>
                </template>
              </el-table-column>

              <!--
                mock_arrcl.indexOf(ids[i]
                :checked=" sels.map((item) => item.id).indexOf(scope.row.id) == -1"

                 <el-checkbox @change="subProj(scope.row)" :disabled="scope.row.id in( sels)" > </el-checkbox>
                 row.id in( this.sels.map((item) => item.id))
                 scope.row.id in(sels.map((item) => item.id))!==-1
                            <el-table-column  label="常规校验数量" min-width="14%"  >
                                <template slot-scope="scope">
                                 <span class="over-content">{{scope.row.count2}}</span>
                                      </template>
                            </el-table-column>
                            <el-table-column  label="全部校验数量" min-width="14%"  >
                                <template slot-scope="scope">
                                 <span class="over-content">{{scope.row.count3}}</span>
                                    </template>
                            </el-table-column> -->
            </el-table>
            <el-col :span="24" class="toolbar">
              <el-pagination
                layout="prev, pager, next"
                @current-change="handleCurrentChange"
                :page-size="20"
                :page-count="total"
                style="float:right;"
              >
              </el-pagination>
            </el-col>
          </el-collapse-item>
        </el-collapse>
      </el-row>
    </el-form>

    <br />
    <br />
    <el-button
      class="return-list"
      type="primary"
      :disabled="this.sels.length === 0"
      style="float: right; margin-right: 15px"
      @click.native="generateScript"
      >生成脚本</el-button
    >

    <el-button
      class="return-list"
      type="primary"
      :disabled="this.sels.length === 0"
      style="float: right; margin-right: 15px"
      @click.native="run"
      >执行</el-button
    >
    <el-dialog
      title="生成脚本"
      :visible.sync="createScriptBox"
      :close-on-click-modal="false"
    >
      <el-form
        :model="generateScriptFrom"
        label-width="120px"
        ref="generateScriptFrom"
      >
        <el-form-item label="脚本名称:">
          <el-input
            v-model="generateScriptFrom.scriptName"
            placeholder="请输入脚本名称"
            maxlength="10"
            show-word-limit
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item label="脚本用途:">
          <el-select
            v-model="generateScriptFrom.application.code_id"
            placeholder="请选择脚本用途"
            filterable
          >
            <el-option
              v-for="(item, index) in generateScriptFrom.application"
              :key="index + ''"
              :label="item.code_name"
              :value="item.code_id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="confirmCreate"
          >确定</el-button
        >
        <el-button size="small" @click="cancelCreateScript">取消</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<!-----页面代码结束----->
<!-----脚本代码开始----->
<script>
import { test } from "../../../../api/api";

import {
  getApiListByProjectID,
  runApi,
  getProjectList,
  getModelList,
  getEnvironmentList,
  getCaseTypeList,
  getApplicationList,
  createScript,
} from "../../../../api/api";
export default {
  data() {
    return {
      radio3: "0",
      total: 0,
      page: 1,
      runPlan: [],
      checkmock: false,
      listLoading: false,
      sels: [], //列表选中列
      mockArr: [],

      mockList: [],

      //checkHeadList: [],
      //checkParameterList: [],
      ParameterType: true,

      model: [],
      checkboxT1: false,
      checkboxT2: true,

      project: [],
      //生成脚本
      createScriptBox: false,
      generateScriptFrom: {
        application: "",
        scriptName: "",
      },

      //radio: "form-data",
      addHeaderFormVisible: false, //增加头部信息
      addParameterFormVisible: false, //增加入参
      radioType: "3",
      caseType: "3",
      result: true,
      activeNames: ["1", "2", "3", "4", "5", "6"],
      id: "",
      request3: false,
      selectable: false,
      flag: true,
      //aaaa:true,
      form: {
        getProjectFirstID: "",
        getEnvironmentFirstID: "",
        getCaseTypeFirstID: "",
        getModelFirstID: "",
        interface_name_zh: "",
        interface_name_en: "",
        status: true,
        requestType: "POST",
        httpType: "HTTP",
        apiAddress: "",
        selectable: false,
        //默认check属性yilai=0  不要勾选 不存在依赖
        headerDict: [
          { key: "", _type: "String", yilai: "0", yilaijiekou: "" }, //依赖默认给1
          { key: "", _type: "String", yilai: "0", yilaijiekou: "" },
        ],
        requestList: [
          { name: "", _type: "String", yilai: "0", yilaijiekou: "" },
          { name: "", _type: "String", yilai: "0", yilaijiekou: "" },
        ],
        MiList: [{ MiURL: "", JMiURL: "" }],
        //MiURL:'',
        //JMiURL:'',
        //requestParameterType: "",

        data: "",
      },
      FormRules: {
        interface_name_zh: [
          { required: true, message: "请输入接口", trigger: "blur" },
          { max: 50, message: "不能超过50个字", trigger: "blur" },
        ],

        getModelFirstID: [
          {
            type: "number",
            required: true,
            message: "请选择项目模块",
            trigger: "blur",
          },
        ],
        getProjectFirstID: [
          {
            type: "number",
            required: true,
            message: "请选择项目",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    cellcb(row) {
      if (row.row.checkStatus === 1 && row.columnIndex === 0) {
        return "myCell";
      }
    },

    handleCurrentChange(val) {
      this.page = val;
      this.getInterfaceChangePage();
    },

    radioChange(val) {
      this.radio3 = val;
    },

    /*****
              获取运行接口列表---翻页事件
            ****/
    getInterfaceChangePage() {
      let self = this;

      let param = {
        project_id: Number(self.form.getProjectFirstID),
        page: self.page,
      };

      $.ajax({
        type: "get",
        url: test + "/api/api/getInterfaceByProjectId",
        async: true,
        data: param,
        headers: {
          Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
        },
        timeout: 5000,
        success: function(data) {
          if (data.code === "999999") {
            self.total = data.total;

            self.runPlan = data.data.data;
          } else {
            self.$message.error({
              message: data.msg,
              center: true,
            });
          }
        },
      });
    },

    /*****
              获取运行接口列表---change下拉框事件
            ****/
    getInterface(value) {
      //let params = { page: self.page, env_name: self.filters.env_name};

      let self = this;

      let param = { project_id: value, page: self.page };

      $.ajax({
        type: "get",
        url: test + "/api/api/getInterfaceByProjectId",
        async: true,
        data: param,
        headers: {
          Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
        },
        timeout: 5000,
        success: function(data) {
          var data_plan = data.data.data;

          var data_plan_all = [];

          if (data.code === "999999") {
            self.total = data.total;
            for (var i = 0; i < data_plan.length; i++) {
              data_plan[i]["mock_status"] = 0;

              data_plan_all.push(data_plan[i]);
            }

            self.runPlan = data_plan_all;
          } else {
            self.$message.error({
              message: data.msg,
              center: true,
            });
          }
        },
      });
    },

    run: function() {
      let ids = this.sels.map((item) => item.id);

      var mock_arrcl = this.mockArr; //mockArr处理

      /******

        var mockList = this.mockArr;
          if (mockList.indexOf(row.id) > -1) {

            //则包含该元素

       */
      var idscl = []; //ids处理
      for (var i = 0; i < ids.length; i++) {
        if (mock_arrcl.indexOf(ids[i]) > -1) {
          //则包含该元素
          idscl.push(ids[i] + "|1");
        } else {
          idscl.push(ids[i] + "|0");
        }
      }

      let self = this;
      this.$confirm("确认执行选中的接口吗？", "提示", {
        type: "warning",
      }).then(() => {
        this.listLoading = true;

        let self = this;
        let params = {
          run_ids: [idscl],
          project_id: Number(self.form.getProjectFirstID),
          environment_id: Number(self.form.getEnvironmentFirstID),
          case_type_code_id: self.radio3,
        };

        let header = {
          "Content-Type": "application/json",
          Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
        };
        runApi(header, params).then((_data) => {
          let { msg, code, data } = _data;

          if (code === "999999") {
            var result_message = data[0].msg;
            result_message = JSON.parse(result_message);

            var resultMessage = "项目名称:" + result_message.项目名称 + ",";
            var resultMessage =
              resultMessage + "环境名称:" + result_message.环境名称 + ",";
            var resultMessage =
              resultMessage + "本批次:" + result_message.本批次 + ",";
            var resultMessage =
              resultMessage +
              "共执行接口数量:" +
              result_message.共执行接口数量 +
              ",";
            var resultMessage =
              resultMessage +
              "执行成功数量:" +
              result_message.执行成功数量 +
              ",";
            var resultMessage =
              resultMessage + "执行失败数量:" + result_message.执行失败数量;

            const confirmText = [
              "项目名称:" + result_message.项目名称,
              "环境名称:" + result_message.环境名称,
              "本批次:" + result_message.本批次,
              "共执行接口数量:" + result_message.共执行接口数量,
              "执行成功数量:" + result_message.执行成功数量,
              "执行失败数量:" + result_message.执行失败数量,
            ];

            const newDatas = [];
            const h = this.$createElement;
            for (const i in confirmText) {
              newDatas.push(h("p", null, confirmText[i]));
            }
            this.$confirm("提示", {
              // title:'执行详情如下',
              message: h("div", null, newDatas),
              showCancelButton: false,
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "info",
            })
              .then(() => {
                //self.$router.push({name: ‘userList’})
                // self.$router.push('/report')
                //  self.$router.push({path:'/report',query:{pici:result_message.本批次}})
                self.$router.push({
                  path: "/echarts_report/pici=" + result_message.本批次,
                });

                //     handleResult: function (index, row) {

                //     let api_id=row.id
                //    this.$router.push({path:'/interface_edit/cid='+api_id})

                // },

                //{path:'/hy/lclj/anxd',query:{bzmc:result_message.本批次}}

                // this.requestSwitchStatus(row)
              })
              .catch(() => {});

            // this.$confirm(resultMessage

            //  , '提示', {type: 'info'})
          } else {
            self.$message.error({
              message: msg,
              center: true,
            });
          }
          //self.getLyzdEnvironmentsList()
        });
      });
    },

    //
    getApplication() {
      let self = this;
      let headers = {
        "Content-Type": "application/json",
        Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
      };
      let params = "";
      getApplicationList(headers, params).then((_data) => {
        let { msg, code, data } = _data;
        if (code === "999999") {
          self.generateScriptFrom.application = data;
        } else {
          self.$message.error({
            message: msg,
            center: true,
          });
        }
      });
    },

    //生成脚本
    generateScript() {
      this.createScriptBox = true;
      this.getApplication();
    },
    //取消生成脚本,并清空输入框
    cancelCreateScript() {
      let self = this;
      self.generateScriptFrom.scriptName = "";
      self.generateScriptFrom.application.code_id = "";
      this.createScriptBox = false;
    },
    //确定生成脚本
    confirmCreate() {
      let ids = this.sels.map((item) => item.id);

      let self = this;
      let params = {
        run_ids: [ids],
        project_id: Number(self.form.getProjectFirstID),
        environment_id: Number(self.form.getEnvironmentFirstID),
        case_type_code_id: self.radio3,
        script_name: self.generateScriptFrom.scriptName,
        application_id: self.generateScriptFrom.application.code_id,
      };
      let headers = {
        "Content-Type": "application/json",
        Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
      };

      if (self.generateScriptFrom.scriptName === "") {
        self.$message({
          showClose: true,
          message: "脚本名称不可以为空",
          type: "error",
        });
      } else if (self.generateScriptFrom.application.code_id === undefined) {
        self.$message({
          showClose: true,
          message: "脚本用途不可以为空",
          type: "error",
        });
      } else {
        createScript(headers, params).then((_data) => {
          let { msg, code, data } = _data;
          if (code === "999999") {
            self.$message({
              showClose: true,
              message: msg,
              type: "success",
            });
            // this.$confirm("脚本生成成功", '提示', {type: 'info'})
          } else {
            self.$message({
              showClose: true,
              message: msg,
              type: "error",
            });
          }
        });
        this.createScriptBox = false;
        self.generateScriptFrom.application.code_id = "";
        self.generateScriptFrom.scriptName = "";
      }
    },

    getArrEqual(arr1, arr2) {
      let newArr = [];
      for (let i = 0; i < arr2.length; i++) {
        for (let j = 0; j < arr1.length; j++) {
          if (arr1[j] === arr2[i]) {
            newArr.push(arr1[j]);
          }
        }
      }
      return newArr;
    },

    selsChange: function(sels, index) {
      let id_check_disable = this.sels.map((item) => item.id);
      var selids = [];

      for (var j = 0; j < sels.length; j++) {
        var selid;
        selid = sels[j].id;

        selids.push(selid);
      }

      var mockList = this.mockArr;
      var newList = [];
      newList = this.getArrEqual(selids, mockList); //取出选择接口的数组和mock选中的数组的共同元素的方法

      this.mockList = newList;

      this.sels = sels;
    },

    checkRequest() {
      let request = this.form.requestType;
      if (request === "GET" || request === "DELETE") {
        this.request3 = false;
      } else {
        this.request3 = true;
      }
    },
    isJsonString(str) {
      try {
        if (typeof JSON.parse(str) === "object") {
          return true;
        }
      } catch (e) {}
      return false;
    },

    subProj: function(row, index) {
      if (this.mockArr == "") {
        var mockList = [];
        mockList.push(row.id);
        this.mockArr = mockList;
        row.mock_status = 1;
      } else {
        var mockList = this.mockArr;
        if (mockList.indexOf(row.id) > -1) {
          //则包含该元素
          const removeArr = [row.id];
          mockList = mockList.filter((a) => !removeArr.includes(a));
          this.mockArr = mockList;
          row.mock_status = 0;
        } else {
          mockList.push(row.id);
          this.mockArr = mockList;
          row.mock_status = 1;
        }
      }
    },

    handleResponseEdit: function(index, row) {
      this.id = index;

      //this.editForm = Object.assign({}, row);
    },

    addInterfaceInfo: function() {
      //保存按钮

      if (this.form.data) {
        if (!this.isJsonString(this.form.data)) {
          this.$message({
            message: "数据错误",
            center: true,
            type: "error",
          });
        } else {
          this.addApi();
        }
      } else if (this.form.data) {
        this.$message({
          message: "数据不全",
          center: true,
          type: "warning",
        });
      } else {
        this.addInterface();
      }
    },

    getCaseType() {
      let self = this;
      let params = {
        project_id: this.$route.params.project_id,
      };
      let headers = {
        "Content-Type": "application/json",
        Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
      };
      getCaseTypeList(headers, params).then((_data) => {
        let { msg, code, data } = _data;
        if (code === "999999") {
          self.caseType = data;

          self.form.getCaseTypeFirstID = self.caseType[0].code_id;
        } else {
          self.$message.error({
            message: msg,
            center: true,
          });
        }
      });
    },
    editParameterSubmit: function() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.form.requestList[this.id] = this.editForm;
          this.addParameterFormVisible = false;
        }
      });
    },
    handleParameterEdit: function(index, row) {
      this.addParameterFormVisible = true;
      this.id = index;
      this.editForm = Object.assign({}, row);
    },

    // demo  下拉菜单从数据库取值
    getProjects() {
      let self = this;
      let params = {
        project_id: this.$route.params.project_id,
      };
      let headers = {
        "Content-Type": "application/json",
        Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
      };
      getProjectList(headers, params).then((_data) => {
        let { msg, code, data } = _data;
        if (code === "999999") {
          var projectjsonArr = new Array();

          for (var i = 0; i < data.length; i++) {
            if (data[i].status == 0) {
              projectjsonArr.push(data[i]);
            }
          }

          self.project = projectjsonArr;
        } else {
          self.$message.error({
            message: msg,
            center: true,
          });
        }
      });
    },

    environments() {
      let self = this;
      let params = {
        project_id: this.$route.params.project_id,
      };
      let headers = {
        "Content-Type": "application/json",
        Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
      };
      getEnvironmentList(headers, params).then((_data) => {
        let { msg, code, data } = _data;
        if (code === "999999") {
          self.env = data;

          self.form.getEnvironmentFirstID = self.env[0].id;
        } else {
          self.$message.error({
            message: msg,
            center: true,
          });
        }
      });
    },

    cellcb(index) {
      // txt.style.display = "none";
      //this.form.responseList.splice(index, 1);

      if (index.row.checkStatus === 1 && index.row.columnIndex === 0) {
        return "myCell";
      }
    },

    changeParameterType() {
      //不要删除这个加密URL用的到
      if (this.radio === "form-data") {
        this.ParameterType = true;
      } else {
        this.ParameterType = false;
      }
    },

    handleChange(val) {},
  },
  watch: {
    radio() {
      this.changeParameterType();
    },
  },
  mounted() {
    this.getProjects();
    this.environments();

    this.getCaseType();
  },
};
</script>
<!--style 样式-->
<style lang="scss" scoped>
.return-list {
  margin-top: 0px;
  margin-bottom: 10px;
  border-radius: 25px;
}
.head-class {
  font-size: 17px;
}
.parameter-a {
  display: block;
}
.parameter-b {
  display: none;
}
.selectInput {
  position: absolute;
  /*margin-left: 7px;*/
  padding-left: 9px;
  width: 180px;
  /*border-radius:0px;*/
  /*height: 38px;*/
  left: 1px;
  border-right: 0px;
}
</style>
<style lang="scss">
.selectInput {
  input {
    border-right: 0px;
    border-radius: 4px 0px 0px 4px;
  }
}
</style>

<style>
.myCell .el-checkbox__input {
  display: none;
}
.over-content {
  width: 80;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.color-red {
  color: red;
  border: 1px solid #e8e8e8;
  padding: 0px 6px 0 9px;
  margin-right: 23px;
}
</style>
